import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useRef, useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import { getSuggestion, saveHistories } from '@/store/actions/search'
import { RootState } from '@/types/store'
import { setLocalHistories } from '@/utils/storage'

const SearchPage = () => {
  const history = useHistory()
  const [keyword, setKeyword] = useState('')
  const dispatch = useDispatch()
  const { suggestions = [], histories = [] } = useSelector(
    (state: RootState) => state.search
  )

  const onChange = (e: string) => {
    setKeyword(e)
    run()
  }
  const { run } = useDebounceFn(
    function () {
      if (!keyword) return
      dispatch(getSuggestion(keyword))
    },
    {
      wait: 500,
    }
  )

  const highLight = (str: string): string => {
    return str.replace(
      new RegExp(keyword, 'ig'),
      (match) => `<span>${match}</span>`
    )
  }
  const search = (key: string) => {
    if (!key) return
    let result = [...histories]
    result = result.filter((item) => item !== key)
    result.unshift(key)
    if (result.length > 10) {
      result = result.slice(0, 10)
    }
    setLocalHistories(result)
    dispatch(saveHistories(result))
    history.push(`/search/result?key=${key}`)
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => search(keyword)}>
            搜索
          </span>
        }
      >
        <SearchBar
          placeholder="请输入关键字搜索"
          value={keyword}
          onChange={onChange}
        />
      </NavBar>

      {
        <div
          className="history"
          style={{
            display: keyword ? 'none' : 'block',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span
              onClick={() => {
                dispatch(saveHistories([]))
              }}
            >
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item: string, index: number) => (
              <span
                className="history-item"
                key={index}
                onClick={() => {
                  search(item)
                }}
              >
                <span className="text-overflow">{item}</span>
                <Icon
                  type="iconbtn_essay_close"
                  onClick={(e) => {
                    e?.stopPropagation()
                    dispatch(saveHistories(histories.filter((v) => v !== item)))
                  }}
                />
              </span>
            ))}
          </div>
        </div>
      }

      <div className={classnames('search-result', keyword ? 'show' : '')}>
        {suggestions.map((item: string, index: number) => {
          if (!item) return null
          return (
            <div
              className="result-item"
              key={index}
              onClick={() => search(item)}
            >
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value text-overflow"
                dangerouslySetInnerHTML={{ __html: highLight(item) }}
              ></div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default SearchPage
